<?php

namespace Nimo\Bundle\BookstoreApiBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('NimoBookstoreApiBundle:Default:index.html.twig', array('name' => $name));
    }
    public function listAction()
    {
        $repo = $this->getDoctrine()->getRepository('NimoBookstoreApiBundle:Book\Book');

        $books = $repo->findAllAsArray();

        $response = new Response(json_encode($books));
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    public function searchAction()
    {
        $repo = $this->getDoctrine()->getRepository('NimoBookstoreApiBundle:Book\Book');

        $books = $repo->searchAsArray();

        foreach($books as $key => $book){
            $books[$key]['introduction'] = substr(strip_tags($book['brief']),0,50);
            unset($books[$key]['brief']);
        }

        $response = new Response(json_encode($books));
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    public function detailAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $repo = $em->getRepository('NimoBookstoreApiBundle:Book\Book');

        $book = $repo->findOneAsArray($id);

        $response = new Response();

        if($book){
            $result['status'] = 'success';
            #$result['book'] = $book;
            $result['book'] = $book->toArray();
            $book->increaseViewCount();
            $book->setLastViewedDate(new \DateTime('now') );
            $em->persist($book);
            $em->flush();
        }
        else {
            $response->setStatusCode(404,'Not found');
            $result['status'] = 'failed';
            $result['error'] = array(
                'code' => 404,
                'message' => 'Not found'
            );
        }

        $response->setContent(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }
}
